package com.software.loginregister.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.software.loginregister.R;
import com.software.loginregister.adapter.HistoryAdapter;
import com.software.loginregister.entity.Works;
import com.software.loginregister.entity.room.WorksCache;
import com.software.loginregister.databasesHelper.AppDatabase;
import com.software.loginregister.databasesHelper.WorksCacheDao;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.util.ArrayList;
import java.util.List;

public class HistoryActivity extends AppCompatActivity {

    private RecyclerView historyList;
    private HistoryAdapter historyAdapter;
    private TextView emptyView;
    private WorksCacheDao worksCacheDao;
    private Gson gson;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_history);

        try {
            historyList = findViewById(R.id.history_list);
            emptyView = findViewById(R.id.empty_view);
            findViewById(R.id.btn_recent_view_back).setOnClickListener(v -> finish());

            setStatusBar();

            LinearLayoutManager layoutManager = new LinearLayoutManager(this);
            layoutManager.setReverseLayout(true);
            layoutManager.setStackFromEnd(true);
            historyList.setLayoutManager(layoutManager);

            worksCacheDao = AppDatabase.getDatabase(this).worksCacheDao();
            gson = new Gson();

            loadBrowsingHistory();
        } catch (Exception e) {
            Log.e("HistoryActivity", "Error initializing HistoryActivity", e);
            Toast.makeText(this, "初始化历史记录页面时出错", Toast.LENGTH_SHORT).show();
            finish();
        }
    }

    private void loadBrowsingHistory() {
        new Thread(() -> {
            try {
                List<WorksCache> cacheList = worksCacheDao.getAllWorks();
                List<Works> historyWorks = new ArrayList<>();

                for (WorksCache cache : cacheList) {
                    Works work = gson.fromJson(cache.getCacheData(), Works.class);
                    historyWorks.add(work);
                }

                runOnUiThread(() -> {
                    if (historyWorks.isEmpty()) {
                        historyList.setVisibility(View.GONE);
                        emptyView.setVisibility(View.VISIBLE);
                    } else {
                        historyList.setVisibility(View.VISIBLE);
                        emptyView.setVisibility(View.GONE);
                        historyAdapter = new HistoryAdapter(this, historyWorks, this::onHistoryItemClick);
                        historyList.setAdapter(historyAdapter);
                    }
                });
            } catch (Exception e) {
                Log.e("HistoryActivity", "Error loading browsing history", e);
                runOnUiThread(() -> {
                    Toast.makeText(this, "加载浏览历史时出错", Toast.LENGTH_SHORT).show();
                    emptyView.setVisibility(View.VISIBLE);
                    historyList.setVisibility(View.GONE);
                });
            }
        }).start();
    }

    private void onHistoryItemClick(Works work) {
        Intent intent = new Intent(this, RecommendDetailActivity.class);
        intent.putExtra("worksId", work.getWorksId());
        intent.putExtra("worksName", work.getWorksName());
        intent.putExtra("photoUrl", work.getPhotoUrl());
        intent.putExtra("description", work.getDescription());
        startActivity(intent);
    }

    private void setStatusBar() {
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.setStatusBarColor(Color.TRANSPARENT);

        View decorView = window.getDecorView();
        int flags = decorView.getSystemUiVisibility();
        flags |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
        decorView.setSystemUiVisibility(flags);
    }
}

